package com.xingkeduo.pojo.json;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.xingkeduo.pojo.query.DeptmentQuery;
import com.xingkeduo.pojo.table.DeptmentTable;
import com.xingkeduo.util.pojo.base.BaseJson;
import com.xingkeduo.util.pojo.domain.Page;
import com.xingkeduo.util.pojo.enums.YesNoEnum;
import com.xingkeduo.util.pojo.exception.InputParamException;
import com.xingkeduo.util.tool.CommonUtil;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;

public class DeptmentJson extends BaseJson {

	public static DeptmentQuery createQueryForDeptment(String json) throws Throwable {
		DeptmentQuery query = new DeptmentQuery();
		JsonNode root = validJson(json);
		if (root == null)
			return query;
		query.setId(validId(root, YesNoEnum.YES));
		return query;
	}

	public static DeptmentTable createTableForModifyDeptment(String urlParam, DeptmentTable deptmentTable) throws Throwable {
		JsonNode root = validJson(urlParam);
		if (root == null)
			throw new InputParamException(InputParamException.Type.INVALID, "参数");

		deptmentTable.setId(validId(root, YesNoEnum.YES));
		return deptmentTable;
	}

	public static ObjectNode toJson(DeptmentTable deptmentTable) {
		ObjectNode root = MAPPER.createObjectNode();

		if (deptmentTable != null)
		{
			root.put("id", deptmentTable.getId());
			root.put("code", deptmentTable.getCode());
			root.put("name", deptmentTable.getName());
			root.put("enname", deptmentTable.getEnname());
			root.put("status", deptmentTable.getStatus());
			//处理时间
			String createdTime =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(deptmentTable.getCreatedTime());
			root.put("createtime", createdTime);
		}

		return root;
	}

	public static ArrayNode toJson(List<DeptmentTable> deptmentTableList) throws Throwable {
		ArrayNode root = MAPPER.createArrayNode();

		if(!CommonUtil.isEmpty(deptmentTableList)){
			for (Iterator<DeptmentTable> iterator = deptmentTableList.iterator(); iterator.hasNext();) {
				root.add(toJson(iterator.next()));
			}
		}

		return root;
	}
	public static ObjectNode toJsonPage(Page<DeptmentTable> page) throws Throwable {
		ObjectNode root = MAPPER.createObjectNode();
		if (page != null)
		{
			root.put("pageNo", page.getPageNo());
			root.put("pageSize", page.getPageSize());
			root.put("pageTotal", page.getPageTotal());
			root.put("recordTotal", page.getRecordTotal());
			root.put("dtoLists", toJson(page.getDtoList()));
		}
		return root;
	}
}
